package org.springframework.data.redis.core;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import lombok.extern.slf4j.Slf4j;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.util.ClassUtils;

import redis.clients.jedis.JedisCluster;

/**
 * 转用自定义的
 * {@link org.springframework.data.redis.core.JedisConnectionWrapper }
 *  增强RedisConnection，将redis  cluster不支持的命令给屏蔽掉
 * @author Jacarri
 * 
 */
@Slf4j
public class JedisConnectionWrapperClusterInvocationHandler implements MethodInterceptor, DisposableBean {

	private JedisCluster jedisCluster;
	private int redirections;
	static Method METHOD_GETCONNECTION = null;
	static Method METHOD_GETCONNECTIONFROMSLOT = null;

	public JedisConnectionWrapperClusterInvocationHandler(JedisCluster jedisCluster, int redirections) {
		this.jedisCluster = jedisCluster;
		this.redirections = redirections;
	}

	protected RedisConnection createRedisConnectionProxy(JedisCluster jedisCluster, int redirections) {
		Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(RedisConnection.class, getClass().getClassLoader());
		return (RedisConnection) Proxy.newProxyInstance(jedisCluster.getClass().getClassLoader(), ifcs,
				new JedisConnectionWrapper(jedisCluster, redirections));
	}

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Class<?> returnType = invocation.getMethod().getReturnType();
		Object returnVal = null;
		// 只拦截获取RedisConnection的getConnection方法
		if (returnType.isAssignableFrom(RedisConnection.class)) {
			returnVal = createRedisConnectionProxy(jedisCluster, redirections);
		} else {
			returnVal = invocation.proceed();
		}
		return returnVal;
	}

	@Override
	public void destroy() throws Exception {
		log.warn("destory jedisCluster.....");
		jedisCluster.close();
	}
}
